package com.douya.security.handler;

import com.douya.common.enums.CommonResultEnums;
import com.douya.common.ex.ApiException;
import com.douya.common.pojo.vo.CommonResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 安全异常处理器
 *
 * @Author hcy
 * @Date 2023/6/15
 */
@Slf4j
@RestControllerAdvice
public class SecurityExceptionHandler {

    /**
     * 处理403异常
     */
    @ExceptionHandler(value = {AccessDeniedException.class})
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public CommonResponseVO<?> handAccessDeniedException(AccessDeniedException e) {
        log.warn("", e);
        return CommonResponseVO.error(CommonResultEnums.FORBIDDEN);
    }

    /**
     * 处理登录验证
     */
    @ExceptionHandler(value = {AuthenticationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public CommonResponseVO<?> handAuthenticationException(AuthenticationException e) {
        log.warn("", e);
        return CommonResponseVO.born(CommonResultEnums.INVALID_PARAMS.getCode(), e.getMessage(), null);
    }

    @ExceptionHandler(ApiException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public CommonResponseVO<?> handApiException(ApiException e) {
        log.warn("", e);
        return CommonResponseVO.born(e.getCode(), e.getMessage(), e.getData());
    }
}
